package com.hy.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hy.order.domain.Order;
import com.hy.order.mapper.OrderMapper;
import com.hy.order.service.OrderTccAction;
import com.hy.storage.util.IdempotentUtil;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@Component
public class OrderTccActionImpl implements OrderTccAction {
    @Resource
    OrderMapper orderMapper;

    @Transactional
    @Override
    public boolean createOrder(BusinessActionContext businessActionContext, Order order) {
        if (Objects.nonNull(IdempotentUtil.getMarker(getClass(),businessActionContext.getXid()))){
            log.info("已执行过try阶段");
            return true;
        }
        order.setStatus(1);
        orderMapper.insertSelective(order);
        log.info("创建订单 ： tcc 一阶段提交");
        IdempotentUtil.addMarker(getClass(),businessActionContext.getXid(),"marker");
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext businessActionContext) {
        if (Objects.isNull(IdempotentUtil.getMarker(getClass(),businessActionContext.getXid()))){
            log.info("已执行过commit阶段");
            return true;
        }

        JSONObject obj = (JSONObject) businessActionContext.getActionContext("order");
        Order order = JSON.parseObject(obj.toJSONString(), Order.class);
        orderMapper.updateByPrimaryKeySelective(order);
        log.info("创建订单：tcc二阶段commit成功");

        IdempotentUtil.removeMarker(getClass(),businessActionContext.getXid());
        return true;

    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext businessActionContext) {
        if (Objects.isNull(IdempotentUtil.getMarker(getClass(),businessActionContext.getXid()))){
            log.info("已执行过rollback阶段");
            return true;
        }

        JSONObject obj = (JSONObject) businessActionContext.getActionContext("order");
        Order order = JSON.parseObject(obj.toJSONString(), Order.class);
        orderMapper.deleteByPrimaryKey(order);
        log.info("创建订单：tcc二阶段回滚成功");
        IdempotentUtil.removeMarker(getClass(),businessActionContext.getXid());
        return true;

    }
}
